<template>
	<view class="page" :data-theme="theme" :style="{'background-image': `url(${backBg})`}">
		<view class="system-height" :style="{height:statusBarHeight}"></view>
		<!-- #ifdef MP -->
		<view class="title-bar" style="height: 43px;">
			<view class="icon" @click="back" v-if="!isHome">
				<image :src="urlDomain+'crmebimage/perset/usersImg/left.png'"></image>
			</view>
			<view class="icon" @click="home" v-else>
				<image :src="urlDomain+'crmebimage/perset/usersImg/home.png'"></image>
			</view>
			账户登录132
		</view>
		<!-- #endif -->
		<view class="wechat_login">
			<view class="img acea-row row-center">
				<image :src="mobileLoginLogo" mode="widthFix" class="image"></image>
			</view>
			<view class="company">{{companyName}}</view>
			
			<!-- 登录方式切换 -->
			<view class="login-tabs">
				<view class="tab-item" :class="{active: loginType === 'phone'}" @click="switchLoginType('phone')">
					手机登录
				</view>
				<view class="tab-item" :class="{active: loginType === 'account'}" @click="switchLoginType('account')">
					账号登录
				</view>
			</view>
			
			<!-- 手机号登录 -->
			<view v-if="loginType === 'phone'" class="login-form">
				<view class="input-item">
					<view class="item">
						<input class="ipt" type="number" v-model="account" placeholder-class='placeholder'
							placeholder="输入手机号" maxlength="11" />
					</view>
				</view>
				<view class="input-item">
					<view class="item acea-row row-between-wrapper">
						<input class="ipt codeIput" type="number" v-model="codeNum" placeholder-class='placeholder'
							placeholder="输入验证码" maxlength="6" />
						<view class="line"></view>
						<button class="code font-num" :disabled="disabled" @click="code">{{text}}</button>
					</view>
				</view>
				<view class="sub_btn" @click="loginBtn">
					立即登录
				</view>
			</view>
			
			<!-- 账号密码登录 -->
			<view v-if="loginType === 'account'" class="login-form">
				<view class="input-item">
					<view class="item">
						<input class="ipt" type="text" v-model="account" placeholder-class='placeholder'
							placeholder="输入登录账户" maxlength="20" />
					</view>
				</view>
				<view class="input-item">
					<view class="item">
						<input class="ipt" type="password" v-model="password" placeholder-class='placeholder'
							placeholder="填写登录密码" maxlength="18" />
					</view>
				</view>
				<view class="sub_btn" @click="loginBtn">
					立即登录
				</view>
			</view>
			
			<!-- 微信登录按钮 -->
			<view class="btn-wrapper" v-if="loginType === 'phone'">
				<!-- #ifdef H5 -->
				<button hover-class="none" @click="wechatLogin" class="btn1 bg-color"><text
						class='iconfont icon-weixin2'></text>微信登录</button>
				<!-- #endif -->
				<!-- #ifdef MP -->
				<button v-if="wxLogin" hover-class="none"
					@click="getUserProfile" class="btn1 bg-color">微信登录</button>
				<view v-else>
					<button v-if="routinePhoneVerification == 1 || routinePhoneVerification.length===3" hover-class="none"
						@click="onUserPhone" class="btn1 bg-color"><text
							class='iconfont'></text>一键绑定手机号</button>
					<button v-if="routinePhoneVerification == 2 || routinePhoneVerification.length===3" hover-class="none"
						@click="onUserPhone('isPhone')" class="btn2">手动绑定手机号</button>
				</view>		
				<!-- #endif -->
			</view>
		</view>
		<block v-if="isUp">
			<mobileLogin :isUp="isUp" :loginConfig="loginConfig" @close="maskClose" :authKey="authKey" @wechatPhone="wechatPhone"></mobileLogin>
		</block>
		<atModel v-if="isPhoneBox" :userPhoneType="true" :isPhoneBox="isPhoneBox" :authKey="authKey"
			:content="getPhoneContent" @closeModel="bindPhoneClose" @confirmModel="confirmModel"></atModel>
	</view>
</template>

<script>
	const app = getApp();
	// 引入Vuex实例（用于获取token）
	import store from '@/store';
	let statusBarHeight = uni.getSystemInfoSync().statusBarHeight + 'px';
	import mobileLogin from '@/components/login_mobile/index.vue'
	import atModel from '@/components/accredit/index.vue'
	import {
		mapGetters
	} from "vuex";
	import {
		getUserPhone
	} from '@/api/public';
	import {
		LOGO_URL,
		EXPIRES_TIME,
		USER_INFO,
		STATE_R_KEY
	} from '@/config/cache';
	import {
		HTTP_REQUEST_URL
	} from '@/config/app';
	import {
		getUserInfo,
		spread,
		loginMobile,
		loginH5,
		registerVerify
	} from '@/api/user.js'
	import sendVerifyCode from "@/mixins/SendVerifyCode";
	import Routine from '@/libs/routine';
	import wechat from "@/libs/wechat";
	export default {
		mixins: [sendVerifyCode],
		data() {
			return {
				urlDomain: this.$Cache.get("imgHost"),
				isUp: false, // 绑定手机号手动输入弹窗
				phone: '',
				statusBarHeight: statusBarHeight,
				isHome: false,
				isPhoneBox: false, //授权手机号弹窗
				code: '',
				authKey: '',
				options: '',
				userInfo: {},
				codeNum: 0,
				pageStyle: {}, //背景图
				theme: app.globalData.theme,
				backBg: '', //背景图片
				getPhoneContent: '申请获取您的手机号用于注册，完成后可使用商城更多功能',
				wxCode: '', //小程序code值
				companyName: app.globalData.companyName, //公司名称
				routinePhoneVerification: app.globalData.routinePhoneVerification, //小程序手机号校验类型（多选）1微信小程序验证 2短信验证
				loginConfig: '' ,//小程序绑定手机号，isPhone其他手机号绑定
				wxLogin: true ,//登录显示
				mobileLoginLogo: app.globalData.mobileLoginLogo, // 登录页logo
				// 登录相关数据
				loginType: 'phone', // 'phone' 或 'account'
				account: '',
				password: ''
			}
		},
		components: {
			mobileLogin,
			atModel
		},
		onLoad(options) {
			//背景图片设置
			switch (app.globalData.theme) {
				case 'theme1':
					this.backBg = `${this.urlDomain}crmebimage/perset/usersImg/wxbj1.png`;
					break;
				case 'theme2':
					this.backBg = `${this.urlDomain}crmebimage/perset/usersImg/wxbj2.png`;
					break;
				case 'theme3':
					this.backBg = `${this.urlDomain}crmebimage/perset/usersImg/wxbj3.png`;
					break;
				case 'theme4':
					this.backBg = `${this.urlDomain}crmebimage/perset/usersImg/wxbj4.png`;
					break;
				case 'theme5':
					this.backBg = `${this.urlDomain}crmebimage/perset/usersImg/wxbj5.png`;
					break;
			}

			let that = this
			// #ifdef H5
			document.body.addEventListener("focusout", () => {
				setTimeout(() => {
					const scrollHeight = document.documentElement.scrollTop || document.body.scrollTop ||
						0;
					window.scrollTo(0, Math.max(scrollHeight - 1, 0));
				}, 100);
			});
			const {
				code,
				state,
				scope
			} = options;
			this.options = options
			// 获取确认授权code
			this.code = code || ''
			if (code && this.options.scope !== 'snsapi_base') {
				let spread = app.globalData.spread ? app.globalData.spread : 0;
				//公众号授权登录回调
				wechat.auth(code, spread).then(res => {
					if (res.type === 'register') {
						this.authKey = res.key;
						this.isUp = true
					}
					if (res.type === 'login') {
						this.$store.commit('LOGIN', {
							token: res.token
						});
						this.$store.commit("SETUID", res.uid);
						this.getUserInfo();
					}
				}).catch(error => {});
			}
			// #endif
			let pages = getCurrentPages();
		},
		methods: {
			// 切换登录类型
			switchLoginType(type) {
				this.loginType = type;
				// 清空输入内容
				this.account = '';
				this.codeNum = '';
				this.password = '';
			},
			
			// 获取验证码
			async code() {
				let that = this;
				if (!that.account) return that.$util.Tips({
					title: '请填写手机号码'
				});
				if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(that.account)) return that.$util.Tips({
					title: '请输入正确的手机号码'
				});
				await registerVerify(that.account).then(res => {
					that.$util.Tips({
						title: res.msg
					});
					that.sendCode();
				}).catch(err => {
					return that.$util.Tips({
						title: err
					})
				})
			},
			
			// 登录逻辑（核心修复）
			loginBtn() {
				let that = this;
				
				// 手机验证码登录
				if (that.loginType === 'phone') {
					// 输入校验
					if (!that.account) return that.$util.Tips({ title: '请填写手机号码' });
					if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(that.account)) {
						return that.$util.Tips({ title: '请输入正确的手机号码' });
					}
					if (!that.codeNum || that.codeNum.length !== 6) {
						return that.$util.Tips({ title: '请填写6位验证码' });
					}
					
					// 调用手机登录接口
					loginMobile({
						phone: that.account,
						code: that.codeNum
					}).then(res => {
						console.log('手机登录接口返回:', res); // 调试日志
						// 兼容后端返回格式（code=200为成功）
						if (res.code === 200 && res.data) {
							that.$store.commit('LOGIN', { token: res.data.token });
							that.$store.commit("SETUID", res.data.uid);
							that.getUserInfo(); // 调用获取用户信息
						} else {
							that.$util.Tips({ title: res.msg || '登录失败' });
						}
					}).catch(err => {
						that.$util.Tips({ title: '登录接口异常: ' + (err.msg || err) });
					});
				}
				
				// 账号密码登录
				if (that.loginType === 'account') {
					// 输入校验
					if (!that.account) return that.$util.Tips({ title: '请填写登录账户' });
					if (!that.password || that.password.length < 6) {
						return that.$util.Tips({ title: '请填写至少6位登录密码' });
					}
					
					// 调用账号密码登录接口
					loginH5({
						account: that.account,
						password: that.password
					}).then(res => {
						console.log('账号登录接口返回:', res); // 调试日志
						// 兼容后端返回格式（code=200为成功）
						if (res.code === 200 && res.data) {
							that.$store.commit('LOGIN', { token: res.data.token });
							that.$store.commit("SETUID", res.data.uid);
							// 打印token确认是否存储成功
							console.log('登录后token:', that.$store.state.token);
							that.getUserInfo(); // 调用获取用户信息
						} else {
							that.$util.Tips({ title: res.msg || '登录失败' });
						}
					}).catch(err => {
						that.$util.Tips({ title: '登录接口异常: ' + (err.msg || err) });
					});
				}
			},
			
			// 获取用户信息（核心修复：携带token+兼容返回格式）
			getUserInfo() {
				let that = this;
				// 显示加载中
				uni.showLoading({ title: '获取用户信息中...' });
				
				getUserInfo().then(res => {
					uni.hideLoading();
					console.log('用户信息接口返回:', res); // 调试日志
					
					// 后端标准格式：{code:200, data:{...}, msg:"success"}
					if (res.code === 200 && res.data) {
						that.userInfo = res.data;
						that.$store.commit("UPDATE_USERINFO", res.data);
						that.$util.Tips({ title: '登录成功', icon: 'success' }, { tab: 3 });
						
						// 处理推广关系
						if (app.globalData.spread) {
							spread(app.globalData.spread).then(res => {});
						}
					} else {
						// 接口返回200但业务失败（如code=401）
						that.$util.Tips({ title: res.msg || '获取用户信息失败' });
					}
				}).catch(err => {
					uni.hideLoading();
					// 网络错误或接口500等异常
					console.error('获取用户信息异常:', err);
					that.$util.Tips({ title: '获取用户信息失败，请重试' });
				});
			},

			//绑定手机号弹窗回调
			confirmModel() {
				this.isPhoneBox = false;
				this.isUp = true
			},
			back() {
				uni.navigateBack();
			},
			home() {
				uni.switchTab({
					url: '/pages/index/index'
				})
			},
			modelCancel() {
				this.isPhoneBox = false;
			},
			// 弹窗关闭
			maskClose() {
				// 保留原逻辑
			},
			bindPhoneClose(data) {
				if (data.isStatus) {
					this.isPhoneBox = false
					this.$util.Tips({
						title: '登录成功',
						icon: 'success'
					}, {
						tab: 3
					})
				} else {
					this.isPhoneBox = false
				}

			},
			// #ifdef MP
			// 绑定手机号
			onUserPhone(type) {
				this.loginConfig = type;
				if (this.loginConfig === 'isPhone') {
					uni.navigateTo({
						url: `/pages/users/app_login/index?code=${this.wxCode}&authKey=${this.authKey}`
					})
				} else {
					this.isPhoneBox = true
				}
			},
			// wx小程序立即登录
			getUserProfile() {
				let self = this;
				uni.showLoading({
					title: '正在登录中'
				});
				const hostSDKVersion = uni.getSystemInfoSync().hostSDKVersion;
				if (Routine.compareVersion(hostSDKVersion, '2.21.2') >= 0) {
					Routine.getCode()
						.then(code => {
							let userInfo = {};
							userInfo.code = code;
							userInfo.spread_spid = app.globalData.spread;
							userInfo.avatar = '';
							userInfo.nickName = '微信用户';
							userInfo.type = 'routine'
							self.getWxUser(code, userInfo);
						})
						.catch(res => {
							uni.hideLoading();
						});
				} else {
					Routine.getUserProfile().then(res => {
							Routine.getCode()
								.then(code => {
									let userInfo = res.userInfo;
									userInfo.code = code;
									userInfo.spread_spid = app.globalData.spread;
									userInfo.avatar = userInfo.userInfo.avatarUrl;
									userInfo.city = userInfo.userInfo.city;
									userInfo.country = userInfo.userInfo.country;
									userInfo.nickName = userInfo.userInfo.nickName;
									userInfo.province = userInfo.userInfo.province;
									userInfo.sex = userInfo.userInfo.gender;
									userInfo.type = 'routine'
									self.getWxUser(code, userInfo);
								})
								.catch(res => {
									uni.hideLoading();
								});
						})
						.catch(res => {
							uni.hideLoading();
						});
				}
			},
			// 小程序登录调用方法
			getWxUser(code, userInfo) {
				this.wxCode = code;
				let self = this;
				Routine.authUserInfo(userInfo.code, userInfo)
					.then(res => {
						self.authKey = res.data.key;
						if (res.data.type === 'register') {
							uni.hideLoading();
							self.wxLogin = false;
						}
						if (res.data.type === 'login') {
							uni.hideLoading();
							self.$store.commit('LOGIN', {
								token: res.data.token
							});
							self.$store.commit("SETUID", res.data.uid);
							self.getUserInfo();
							if (app.globalData.spread) {
								spread(app.globalData.spread).then(res => {})
							}
							self.$util.Tips({
								title: res,
								icon: 'success'
							}, {
								tab: 3
							})
						}
					})
					.catch(res => {
						uni.hideLoading();
						uni.showToast({
							title: res,
							icon: 'none',
							duration: 2000
						});
					});
			},
			// #endif
			// #ifdef H5
			// 获取url参数
			getQueryString(name) {
				var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
				var reg_rewrite = new RegExp("(^|/)" + name + "/([^/]*)(/|$)", "i");
				var r = window.location.search.substr(1).match(reg);
				var q = window.location.pathname.substr(1).match(reg_rewrite);
				if (r != null) {
					return unescape(r[2]);
				} else if (q != null) {
					return unescape(q[2]);
				} else {
					return null;
				}
			},
			// 公众号登录
			wechatLogin() {
				if (!this.code && this.options.scope !== 'snsapi_base') {
					this.$wechat.oAuth('snsapi_userinfo', '/pages/users/wechat_login/index');
				} else {
					this.isUp = true;
				}
			},
			// 输入手机号后的回调
			wechatPhone() {
				this.$Cache.clear('snsapiKey');
				if (this.options.back_url) {
					let url = uni.getStorageSync('snRouter');
					url = url.indexOf('/pages/index/index') != -1 ? '/' : url;
					if (url.indexOf('/pages/users/wechat_login/index') !== -1) {
						url = '/';
					}
					if (!url) {
						url = '/pages/index/index';
					}
					this.isUp = false
					uni.showToast({
						title: '登录成功',
						icon: 'none'
					})
					setTimeout(res => {
						location.href = url
					}, 800)
				} else {
					uni.navigateBack()
				}
			}
			// #endif
		}
	}
</script>
<style lang="scss">
	page {
		background: #fff;
		height: 100%;
	}
</style>
<style lang="scss" scoped>
	.icon-weixin2{
		margin-right: 10rpx;
	}
	.company {
		font-size: 40rpx;
		color: #333;
		text-align: center;
		font-weight: 500;
		margin: 32rpx 0 96rpx 0;
	}

	.page {
		background: #fff;
		height: 100%;
		background-size: contain;
		background-repeat: no-repeat;
	}

	.wechat_login {
		padding-top: 100rpx;
		
		.img{
			display: flex;
			justify-content: center;
			align-items: center;
		}
		.img .image {
			width: 152rpx;
			height: 152rpx;
			margin: 0 auto;
			
		}
		
		.login-tabs {
			display: flex;
			margin: 40rpx 66rpx;
			border-bottom: 1px solid #f0f0f0;
			
			.tab-item {
				flex: 1;
				text-align: center;
				padding: 20rpx 0;
				font-size: 28rpx;
				color: #999;
				position: relative;
				
				&.active {
					color: $theme-color;
					
					&::after {
						content: '';
						position: absolute;
						bottom: 0;
						left: 50%;
						transform: translateX(-50%);
						width: 60rpx;
						height: 4rpx;
						background: $theme-color;
						border-radius: 2rpx;
					}
				}
			}
		}
		
		.login-form {
			padding: 0 66rpx;
			
			.input-item {
				margin-bottom: 32rpx;
				
				.item {
					background: #F5F5F5;
					border-radius: 45rpx;
					padding: 0 32rpx;
					height: 88rpx;
					display: flex;
					align-items: center;
					
					.ipt {
						flex: 1;
						font-size: 28rpx;
						color: #333;
						
						&.codeIput {
							width: 300rpx;
						}
					}
					
					.placeholder {
						color: #BBBBBB;
						font-size: 28rpx;
					}
					
					.line {
						width: 2rpx;
						height: 28rpx;
						background: #CCCCCC;
						margin: 0 20rpx;
					}
					
					.code {
						background: none;
						font-size: 28rpx;
						color: $theme-color;
						
						&[disabled] {
							color: #999;
						}
					}
				}
			}
			
			.sub_btn {
				width: 100%;
				height: 86rpx;
				line-height: 86rpx;
				margin-top: 40rpx;
				background-color: $theme-color;
				border-radius: 43rpx;
				color: #fff;
				font-size: 28rpx;
				text-align: center;
			}
		}

		.btn-wrapper {
			margin-top: 36rpx;
			padding: 0 66rpx;

			button {
				width: 100%;
				height: 86rpx;
				line-height: 84rpx;
				margin-bottom: 32rpx;
				border-radius: 120rpx;
				font-size: 32rpx;
				background-color: #333;

				&.btn1 {
					color: #00aa00;
				}

				&.btn2 {
					color: #666666;
					border: 2px solid #aaffff;
				}
			}
		}
	}

	.title-bar {
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 36rpx;
	}

	.icon {
		position: absolute;
		left: 30rpx;
		top: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 86rpx;
		height: 86rpx;

		image {
			width: 50rpx;
			height: 50rpx;
		}
	}
</style>